<?php

/**
 * Order actions.
 *
 * @package    ProdAssistant
 * @subpackage Order
 * @author     Paweł Świtalla
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class OrderActions extends sfActions
{
  public function postExecute()
  {
    if($this->getRequest()->isXmlHttpRequest() && isset($this->form))
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      if($errors != '')
      {
        $this->getResponse()->setContent('error@'.$errors."#");
        return sfView::NONE;
      }
    }
  }
  
  public function executeSendOrder(sfWebRequest $request)
  {
    $ordersId = $request->getParameter('id');
    if(!is_array($ordersId)) $ordersId = array($ordersId);
    foreach($ordersId as $id)
    {
      $this->getRequest()->setParameter('id', $id);
      $order = Doctrine_Core::getTable('StoreOrder')->find($id);
      $string = $this->getController()->getPresentationFor('Order', 'showEmail');
      
      $user = $this->getUser()->getAttribute('userObject');
      $username = Settings::getSettings('email_username', $user);
      $password = Settings::getSettings('email_password', $user);
  
      $transport = Swift_SmtpTransport::newInstance('arskomfort.nazwa.pl', 465, 'ssl')
          ->setUsername($username)
          ->setPassword($password);
          
      $mailer = Swift_Mailer::newInstance($transport);
      $message = Swift_Message::newInstance()
                      ->setFrom(array($username => 'ARS KOMFORT SERWIS - Zamówienia'))
                      ->setCc(array($user->getEmail() => $user->getFirstName().' '.$user->getLastName()))
                      ->setTo($order->getDeliverer()->getEmail())
                      ->setReadReceiptTo($user->getEmail())
                      ->setSubject('Zamówienie '.$order->getNumber())
                      ->setBody($string, 'text/html');
      if($mailer->send($message)) $order->setStatus(1)->save();
      //$order->setStatus(1)->save();
    }
                    
    $core = PACore::getInstance();
    if($request->isXmlHttpRequest()) $this->getResponse()->setContent('location@'.$core->generateAppUrl('Store', 'storeOrderHomepage').'#');
    else $this->redirect($core->generateAppUrl('Store', 'storeOrderHomepage'));
    return sfView::NONE;
  }

  public function executeCreate(sfWebRequest $request)
  {
    $core = PACore::getInstance();
    $url = $core->generateAppUrl('Store', 'storeOrderHomepage');
    if($request->hasParameter('demand') || $request->isMethod('post'))
    {
      $this->demand = Doctrine_Core::getTable('ProductionDemand')->find($request->getParameter('demand'));
      $this->demandItems = $this->demand->getDemandItems();
      $category = $this->demand->getCategory();
      $deliverer = $this->demand->getDeliverer();
      $query = DelivererCategories::getCategoryQuery($this->demand->getCategory()->getId());
      
      $parameters = $request->getParameter('store_order');
      $this->form = new StoreOrderForm();
      
      if(!is_null($deliverer->getId()))
      {
        $parameters['deliverer_id'] = $deliverer->getId();
        $choices = array();
        $choices[$deliverer->getId()] = $deliverer->getName();
        $this->form->setWidget('deliverer_id', new sfWidgetFormChoice(array('choices' => $choices)));
      }
      elseif($query->count() > 0)
      {
        $choices = array();
        foreach($query->execute() as $delivererCategory)
        {
          $choices[$delivererCategory->getDeliverer()->getId()] = $delivererCategory->getDeliverer()->getName(); 
        }
        $this->form->setWidget('deliverer_id', new sfWidgetFormChoice(array('choices' => $choices)));
      }
      
      if($request->getParameter('demand'))
      {
        $parameters['user_id'] = $this->getUser()->getAttribute('userObject')->getId();
        $parameters['demand_id'] = $this->demand->getId();
        if(!isset($parameters['deliverer_id'])) $parameters['deliverer_id'] = 9999;
        
        if($request->isMethod('post')) $this->form->bind($parameters);
        if($this->form->isValid())
        {
          if($parameters['deliverer_id'] == 9999 && $request->hasParameter('store_order_items'))
          {
            $storeOrderItems = $request->getParameter('store_order_items');
            $order = new PartialStoreOrder();
            $orders = $order->save($storeOrderItems, $parameters, $this->getUser()->getAttribute('userObject'));
            $ids = array();
            foreach($orders as $order)
            {
              $ids[] = $order->getId();
            }
            $this->getRequest()->setParameter('id', $ids);
            $this->forward('Order', 'sendOrder');
          }
          else
          {
            $order = $this->form->save();
            $order->setDataFromDemand($this->demand);
            $order->setDelivererId($parameters['deliverer_id']);
            $order->setUserId($parameters['user_id']);
            $order->setStatus(0);
            $order->setNumber("ZM-".$order->getDemand()->getProject()->getShortcut()."-".date("Y-m-d", strtotime($order->getCreatedAt()))."-".$order->getId());
            $order->save();
            $this->getRequest()->setParameter('id', array($order->getId()));
            $this->forward('Order', 'sendOrder');
          }
          
          if($request->isXmlHttpRequest())
          {
            $this->getResponse()->setContent('location@'.$url."#");
            return sfView::NONE;
          }
          else $this->redirect($url);
        }
      }
      else
      {
        $this->error = 'Kategoria: '.$category->getName().' - nie przypisano żadnego kontrahenta.';
        return sfView::ERROR;
      }
    }
    else $this->redirect($core->generateAppUrl('Store', 'selectDemand'));
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $order = Doctrine_Core::getTable('StoreOrder')->find($request->getParameter('id'));
    if($order instanceof StoreOrder)
    {
      $order->delete();
    }
    $this->redirect($request->getReferer());
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $core = PACore::getInstance();
    $url = $core->generateAppUrl('Store', 'storeOrderHomepage');
    if($request->hasParameter('id') || $request->isMethod('post'))
    {
      $this->order = Doctrine_Core::getTable('StoreOrder')->find($request->getParameter('id'));
      $this->orderItems = $this->order->getOrderItems();
      
      $this->form = new StoreOrderUpdateForm();
      if($request->isMethod('post'))
      {
        $updateAll = $request->getParameter('update_all');
        if($updateAll == 'true')
        {
          $this->order->updateStatus();
        }
        else
        {
          $values = $request->getParameter('items_list_values');
          $this->order->updateStatus($values);
        }
        if($request->isXmlHttpRequest())
        {
          $this->getResponse()->setContent('location@'.$url."#");
          return sfView::NONE;
        }
        else $this->redirect($url);
      }
    }
    else $this->redirect($core->generateAppUrl('Store', 'storeOrderHomapage'));
  }
  
  public function executeShow(sfWebRequest $request)
  {
    $order = array();
    if(!$request->hasParameter('itemId'))
    {
      $this->order = Doctrine_Core::getTable('StoreOrder')->find($request->getParameter('id'));
      $order = Doctrine_Query::create()
              ->select('s.id, p.id, oi.ordered_value, oi.supplied_value, i.name, i.id, c.quantityUnit')
              ->from('StoreOrder s')
              ->leftJoin('s.OrderItems oi')
              ->leftJoin('oi.StoreItem i')
              ->leftJoin('i.Category c')
              ->where('s.id = ?', $request->getParameter('id'))
              ->execute()
              ->toArray();
    }
    else
    {
      $this->order = StoreOrderTable::getLastWithItem($request->getParameter('itemId'));

      if($this->order instanceof StoreOrder)
      {
        $order = Doctrine_Query::create()
              ->select('s.id, p.id, oi.ordered_value, oi.supplied_value, i.name, i.id, c.quantityUnit')
              ->from('StoreOrder s')
              ->leftJoin('s.OrderItems oi')
              ->leftJoin('oi.StoreItem i')
              ->leftJoin('i.Category c')
              ->where('s.id = ?', $this->order->getId())
              ->execute()
              ->toArray();
      }
    }
    
    if(count($order) > 0)
    {
      $this->items = array();
      foreach($order[0]['OrderItems'] as $item)
      {
        $this->items[] = array('name' => $item['StoreItem']['name'], 'supplied_value' => $item['supplied_value'], 'ordered_value' => $item['ordered_value'], 'quantityUnit' => $item['StoreItem']['Category']['quantityUnit'], 'annotation' => '', 'symbol' => StoreItem::getSymbol($item['StoreItem']['id']));
      }
    }
    $this->setLayout(PACore::getLayoutsDir()."/document");
  }

  public function executeShowEmail(sfWebRequest $request)
  {
    $user = $this->getUser()->getAttribute('userObject');
    $this->companyName = Settings::getSettings('company_name', $user);
    $this->companyAddress = Settings::getSettings('company_address', $user);

    $order = array();
    $this->order = Doctrine_Core::getTable('StoreOrder')->find($request->getParameter('id'));
    $order = Doctrine_Query::create()
            ->select('s.id, p.id, oi.ordered_value, oi.supplied_value, i.name, i.id, c.quantityUnit')
            ->from('StoreOrder s')
            ->leftJoin('s.OrderItems oi')
            ->leftJoin('oi.StoreItem i')
            ->leftJoin('i.Category c')
            ->where('s.id = ?', $request->getParameter('id'))
            ->execute()
            ->toArray();

    if(count($order) > 0)
    {
      $this->items = array();
      foreach($order[0]['OrderItems'] as $item)
      {
        $this->items[] = array('name' => $item['StoreItem']['name'], 'supplied_value' => $item['supplied_value'], 'ordered_value' => $item['ordered_value'], 'quantityUnit' => $item['StoreItem']['Category']['quantityUnit'], 'annotation' => '', 'symbol' => StoreItem::getSymbol($item['StoreItem']['id']));
      }
    }
    $this->setLayout(PACore::getLayoutsDir()."/email");
  }
  
  public function executeList(sfWebRequest $request)
  {
    $this->status = array(0 => 'Nowe', 1 => 'Realizowane', 2 => 'Częściowe', 3 => 'Gotowe', 10 => 'Wstrzymane', 11 => 'Anulowane');
    if(!$request->hasParameter('itemId'))
    {
      $this->orders = Doctrine_Core::getTable('StoreOrder')->findAll();
    }
    else
    {
      $this->orders = StoreOrderTable::getAllWithItem($request->getParameter('itemId'));
      $this->setLayout(PACore::getLayoutsDir().'/clear');
    }
  }
  
  public function executeSelectDemand(sfWebRequest $request)
  {
    $this->form = new sfForm();
    $query = Doctrine_Query::create()
          ->select('d.*')
          ->from('ProductionDemand d');
    
    if($query->execute()->count() == 0) $this->showForm = false;
    else $this->showForm = true;
    $widget = new sfWidgetFormDoctrineChoice(array('model' => 'ProductionDemand', 'label' => 'Wybierz zapotrzebowanie:', 'method' => 'getSelectDemandName', 'query' => $query));
    $this->form->setWidget('demand_id', $widget);
    if($request->isMethod('post'))
    {
      $this->demandId = $request->getParameter('demand_id');
      if($request->isXmlHttpRequest())
      {
        $core = PACore::getInstance();
        $url = $core->generateAppUrl('Store', 'createOrder', null, array('demand' => $this->demandId));
        $this->getResponse()->setContent('location@'.$url.'#');
        return sfView::NONE;
      }
    }
    $this->setLayout('clear');
  }
  
  public function executeChangeStatus(sfWebRequest $request)
  {
    /* Możliwe statusy
     * 
     * 0 - Nowe
     * 1 - Realizowane
     * 2 - Częściowe
     * 3 - Gotowe
     * 
     * 10 - Wstrzymane
     * 11 - Anulowane
    */
    
    
  }
}
